import 'package:async/src/result/result.dart';
import 'package:boss/color_constant.dart';
import 'package:boss/main.dart';
import 'package:boss/models/qr_statistics_detail_page.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/widget/button/radius_button.dart';
import 'package:boss/ui/widget/calendar/util/date_util.dart';
import 'package:boss/ui/widget/calendar_bar.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/loader/empty_widget.dart';
import 'package:boss/ui/widget/loader/loader_pull_refresh.dart';
import 'package:boss/ui/widget/popupMenu/popupMenu.dart' as popup;
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';
import 'package:router/annotation.dart';
import 'package:flustars/flustars.dart' as flustars;

@RouterConfig(ReportTableQrDetailPage.pageName)
class ReportTableQrDetailPage extends StatefulWidget {
  static const pageName = '/ReportTableQrDetailPage';

  @override
  _ReportTableQrDetailPageState createState() => _ReportTableQrDetailPageState();
}

class _ReportTableQrDetailPageState extends BaseState<ReportTableQrDetailPage> {
  _ReportTableQrDetailPageState() : super(ReportTableQrDetailPage.pageName);

  DateTime startTime;
  DateTime endTime;

  List<String> refoundMenus = ['全部', '有退款'];
  int refoundMenuIndex = 0;
  List<String> payMenus = ['全部', '微信', '支付宝'];
  List<String> payValueMenus = [null, 'WX', 'ALIPAY'];
  int payMenuIndex = 0;

  List<QrStatisticsDetail> data = [];

  bool isLoading = false;

  GlobalKey<LoaderPullRefreshState> refreshKey = GlobalKey<LoaderPullRefreshState>();

  @override
  void initState() {
    super.initState();

    startTime = DateTime.now();
    endTime = DateTime.now();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CenterTitleAppBar(title: '收款明细'),
      body: Column(
        children: [
          Container(
            padding: EdgeInsets.all(30.w),
            child: Row(
              children: [
                Expanded(
                  child: CalendarBar(
                    enabled: !isLoading,
                    startDateTime: startTime,
                    endDateTime: endTime,
                    onDateTimeChanged: (List<DateTime> dateTime) {
                      setState(() {
                        startTime = dateTime[0];
                        endTime = dateTime[1];
                      });
                    },
                  ),
                ),
                RadiusButton(
                  title: '查询',
                  width: 160.w,
                  height: 60.w,
                  margin: EdgeInsets.only(left: 20.w),
                  onTap: refresh,
                  enabled: !isLoading,
                ),
              ],
            ),
          ),
          Container(
            height: 60.w,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                popup.PopupMenuButton(
                  child: buildPopMenuButton('有无退款'),
                  items: refoundMenus,
                  index: refoundMenuIndex,
                  onItemTap: (index) {
                    setState(() {
                      refoundMenuIndex = index;
                    });

                    refresh();
                  },
                  enabled: !isLoading,
                ),
                popup.PopupMenuButton(
                  child: buildPopMenuButton('支付平台'),
                  items: payMenus,
                  index: payMenuIndex,
                  onItemTap: (index) {
                    setState(() {
                      payMenuIndex = index;
                    });

                    refresh();
                  },
                  enabled: !isLoading,
                ),
              ],
            ),
          ),
          Expanded(
            child: LoaderPullRefresh<QrStatisticsDetail>(
              key: refreshKey,
              loadTask: loadTask,
              refreshTask: refreshTask,
              builder: (context) {
                if (data.isEmpty) {
                  return EmptyWidget(title: '暂无收款记录~');
                }

                return ListView.builder(
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  itemBuilder: (context, index) {
                    if (index == 0) {
                      return buildTableHeader();
                    }

                    final current = data[index - 1];

                    return buildTableRow(current);
                  },
                  // itemCount: data.length + 1,
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget buildPopMenuButton(String title) {
    return Row(
      children: [
        Container(
          child: Text(title, style: TextStyleConstant().normal_1_28),
          margin: EdgeInsets.only(right: 6.w),
        ),
        BaseImage(
          'assets/image/report_qr_arrow_down.png',
          width: 14.w,
          height: 10.w,
        ),
      ],
    );
  }

  void refresh() {
    refreshKey.currentState.refresh(needMove: true);
  }

  Future<Result<List<QrStatisticsDetail>>> loadTask() {
    return queryData(data.length ~/ 10 + 1);
  }

  Future<Result<List<QrStatisticsDetail>>> refreshTask() {
    return queryData(0);
  }

  Future<Result<List<QrStatisticsDetail>>> queryData(int page) async {
    isLoading = true;

    try {
      final res = await api.queryReportTableQrDetail(
        formatDatTime2String(startTime),
        formatDatTime2String(endTime),
        refoundMenuIndex,
        page,
        10,
        channelName: payValueMenus[payMenuIndex],
      );
      if (!res.successful()) {
        return Result.error(res.msg);
      }

      if (page == 0) {
        data = res.data.items;
      } else {
        data.addAll(res.data.items);
      }

      return Result.value(res.data.items);
    } finally {
      isLoading = false;
    }
  }

  String formatDatTime2String(DateTime dateTime, {bool isEndDateTime = false}) {
    DateTime time = dateTime;
    if (isEndDateTime) {
      time = DateUtils.endOfTheDay(dateTime);
    } else {
      time = DateUtils.startOfTheDay(dateTime);
    }
    return flustars.DateUtil.formatDate(time, format: flustars.DateFormats.full);
  }

  Widget buildTableHeader() {
    return DefaultTextStyle(
      style: TextStyleConstant().normal_2_28,
      child: Container(
        height: 90.w,
        padding: EdgeInsets.symmetric(horizontal: 30.w),
        decoration: BoxDecoration(
          color: ColorConstant.ffcc,
          borderRadius: BorderRadius.only(topLeft: Radius.circular(10), topRight: Radius.circular(10)),
        ),
        child: Row(
          children: [
            Expanded(child: Text('交易时间'), flex: 3),
            Expanded(child: Center(child: Text('支付平台')), flex: 2),
            Expanded(child: Text('金额', textAlign: TextAlign.end), flex: 1),
          ],
        ),
      ),
    );
  }

  Widget buildTableRow(QrStatisticsDetail value) {
    return DefaultTextStyle(
      style: TextStyleConstant().normal_1_28,
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 30.w),
        decoration: BoxDecoration(border: Border(bottom: BorderSide(color: ColorConstant.e5e5, width: 1.px))),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Text(flustars.DateUtil.formatDateStr(value.payTime, format: flustars.DateFormats.y_mo_d_h_m)),
              flex: 3,
            ),
            Expanded(
              child: Center(child: Text(value.payTypeVO.typeName)),
              flex: 2,
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text('+' + AmountUtil.price2String(value.totalFee)),
                  if (value.refundAmount > 0)
                    Container(
                      margin: EdgeInsets.only(top: 20.w),
                      child: Text(
                        value.totalFee == value.refundAmount ? '已全额退款' : '-' + AmountUtil.price2String(value.refundAmount),
                        style: TextStyleConstant().origin_22,
                      ),
                    ),
                ],
              ),
              flex: 1,
            ),
          ],
        ),
      ),
    );
  }
}
